import json
import select
import socket
import sys
import time

HOST = 'localhost'
PORT = 6546

ssock = None

def listen():
	global ssock
	input_buf = ''
	#ssock = socket.socket()
	ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	ssock.connect((HOST, PORT))
	all_socks = [ssock, sys.stdin]
	print(all_socks)
	while True:
		readable, writable, exceptional = select.select(all_socks, [], all_socks)
		if len(exceptional) >= 1:
			print('exceptional! %s' % (exceptional,))
			continue
		if len(readable) >= 1:
			s = readable[0]

			if s == sys.stdin: # keyboard
				#input_buf += inp
				bmsg = s.readline()
				if len(bmsg) <= 0:
					print('read 0; hangup')
					exit(3)
				msg = bmsg.strip()
				parse(msg)
			elif s == ssock: # server
				bmsg = s.recv(1024)
				if len(bmsg) <= 0:
					print('read 0; hangup')
					exit(3)
				msg = str(bmsg, 'utf-8').strip()
				print('from server:', msg)
			else:
				print('unknown socket:', s)
				exit(2)

def send_msg(msg):
	jmsg = json.dumps(msg)
	print('msg to send:', jmsg)
	ssock.send(bytes(jmsg, 'utf-8'))

def print_not_implemented():
	print('not_implemented')

def process_info(msg):
	print_not_implemented()

def process_query(msg):
	print_not_implemented()

def parse_msg(jmsg):
	try:
		msg = json.loads(jmsg)
		typ = msg.get('type')
		if typ == 'info':
			process_info(msg)
		elif typ == 'query':
			process_query(msg)
		else:
			print('unknown type:', typ)

		print('info:', msg)

	except json.decoder.JSONDecodeError:
		print('unparsable message:', jmsg)

def build_action(action, rest = {}):
	ret = { 'action': action}
	ret.update(rest)
	return ret

def start_game():
	return build_action('start')

def give_card(card):
	return build_action('give_card', { 'card': card })

def parse(line):
	print('parse')
	line = line.strip()

	if len(line) < 1:
		return

	cmd = line[0]
	arg = line[1:].strip()
	print(cmd, arg)

	if cmd == 'g':
		msg = give_card(int(arg))
		send_msg(msg)
	elif cmd == 's':
		msg = start_game()
		send_msg(msg)
	else:
		print('unknown cmd:', cmd)

if __name__ == '__main__':
	try:
		while True:
			#line = input()
			#parse(line)
			listen()
	except KeyboardInterrupt:
		print('interrupt - exiting')
		#TODO: close
		exit(9)
